#!/usr/bin/env python3
"""
CPU占用对比可视化工具
绘制 enrigindec vs avdec_h264 的CPU占用对比图表
"""

import csv
import matplotlib.pyplot as plt
import numpy as np
from pathlib import Path

def read_cpu_data(filename):
    """读取CPU数据CSV文件"""
    timestamps = []
    cpu_values = []
    
    with open(filename, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            try:
                timestamps.append(float(row['timestamp']))
                cpu_values.append(float(row['cpu_percent']))
            except (ValueError, KeyError):
                continue
    
    # 归一化时间戳（从0开始）
    if timestamps:
        start_time = timestamps[0]
        timestamps = [t - start_time for t in timestamps]
    
    return timestamps, cpu_values

def calculate_stats(cpu_values):
    """计算统计数据"""
    if not cpu_values:
        return {}
    
    return {
        'mean': np.mean(cpu_values),
        'max': np.max(cpu_values),
        'min': np.min(cpu_values),
        'std': np.std(cpu_values),
        'median': np.median(cpu_values)
    }

def plot_comparison():
    """绘制对比图表"""
    
    # 读取数据
    sw_times, sw_cpu = read_cpu_data('cpu_avdec_h264.csv')
    hw_times, hw_cpu = read_cpu_data('cpu_enrigindec.csv')
    
    if not sw_cpu or not hw_cpu:
        print("错误: 无法读取CPU数据文件")
        return
    
    # 计算统计
    sw_stats = calculate_stats(sw_cpu)
    hw_stats = calculate_stats(hw_cpu)
    
    # 创建图表
    fig, axes = plt.subplots(2, 2, figsize=(15, 10))
    fig.suptitle('解码器CPU占用对比: enrigindec (硬件) vs avdec_h264 (软件)', 
                 fontsize=16, fontweight='bold')
    
    # 1. CPU占用时序图
    ax1 = axes[0, 0]
    ax1.plot(sw_times, sw_cpu, label='avdec_h264 (软件)', 
             color='#FF6B6B', linewidth=2, alpha=0.8)
    ax1.plot(hw_times, hw_cpu, label='enrigindec (硬件)', 
             color='#4ECDC4', linewidth=2, alpha=0.8)
    ax1.axhline(y=sw_stats['mean'], color='#FF6B6B', 
                linestyle='--', alpha=0.5, label=f'软件平均: {sw_stats["mean"]:.1f}%')
    ax1.axhline(y=hw_stats['mean'], color='#4ECDC4', 
                linestyle='--', alpha=0.5, label=f'硬件平均: {hw_stats["mean"]:.1f}%')
    ax1.set_xlabel('时间 (秒)', fontsize=12)
    ax1.set_ylabel('CPU占用 (%)', fontsize=12)
    ax1.set_title('CPU占用时序对比', fontsize=14, fontweight='bold')
    ax1.legend(loc='upper right')
    ax1.grid(True, alpha=0.3)
    
    # 2. 统计对比柱状图
    ax2 = axes[0, 1]
    metrics = ['平均', '最大', '最小', '标准差']
    sw_values = [sw_stats['mean'], sw_stats['max'], sw_stats['min'], sw_stats['std']]
    hw_values = [hw_stats['mean'], hw_stats['max'], hw_stats['min'], hw_stats['std']]
    
    x = np.arange(len(metrics))
    width = 0.35
    
    bars1 = ax2.bar(x - width/2, sw_values, width, label='avdec_h264 (软件)',
                    color='#FF6B6B', alpha=0.8)
    bars2 = ax2.bar(x + width/2, hw_values, width, label='enrigindec (硬件)',
                    color='#4ECDC4', alpha=0.8)
    
    ax2.set_xlabel('指标', fontsize=12)
    ax2.set_ylabel('CPU占用 (%)', fontsize=12)
    ax2.set_title('统计指标对比', fontsize=14, fontweight='bold')
    ax2.set_xticks(x)
    ax2.set_xticklabels(metrics)
    ax2.legend()
    ax2.grid(True, alpha=0.3, axis='y')
    
    # 添加数值标签
    for bars in [bars1, bars2]:
        for bar in bars:
            height = bar.get_height()
            ax2.text(bar.get_x() + bar.get_width()/2., height,
                    f'{height:.1f}',
                    ha='center', va='bottom', fontsize=9)
    
    # 3. CPU分布直方图
    ax3 = axes[1, 0]
    ax3.hist(sw_cpu, bins=30, alpha=0.6, label='avdec_h264 (软件)',
             color='#FF6B6B', edgecolor='black')
    ax3.hist(hw_cpu, bins=30, alpha=0.6, label='enrigindec (硬件)',
             color='#4ECDC4', edgecolor='black')
    ax3.set_xlabel('CPU占用 (%)', fontsize=12)
    ax3.set_ylabel('频次', fontsize=12)
    ax3.set_title('CPU占用分布', fontsize=14, fontweight='bold')
    ax3.legend()
    ax3.grid(True, alpha=0.3, axis='y')
    
    # 4. 节省百分比和关键指标
    ax4 = axes[1, 1]
    ax4.axis('off')
    
    # 计算节省百分比
    cpu_saving = (sw_stats['mean'] - hw_stats['mean']) / sw_stats['mean'] * 100
    peak_reduction = (sw_stats['max'] - hw_stats['max']) / sw_stats['max'] * 100
    stability_improvement = (sw_stats['std'] - hw_stats['std']) / sw_stats['std'] * 100
    
    # 创建文本摘要
    summary_text = f"""
    ╔═══════════════════════════════════════╗
    ║        关键性能指标对比               ║
    ╚═══════════════════════════════════════╝
    
    📊 CPU占用对比:
    ├─ avdec_h264:  {sw_stats['mean']:.2f}%
    ├─ enrigindec:  {hw_stats['mean']:.2f}%
    └─ 节省:        {cpu_saving:.1f}% ⬇️
    
    📈 峰值CPU对比:
    ├─ avdec_h264:  {sw_stats['max']:.2f}%
    ├─ enrigindec:  {hw_stats['max']:.2f}%
    └─ 降低:        {peak_reduction:.1f}% ⬇️
    
    📉 稳定性对比 (标准差):
    ├─ avdec_h264:  {sw_stats['std']:.2f}%
    ├─ enrigindec:  {hw_stats['std']:.2f}%
    └─ 改善:        {stability_improvement:.1f}% ⬆️
    
    ✅ 结论:
    硬件解码器 enrigindec 在CPU占用、
    峰值控制和稳定性方面均优于软件
    解码器 avdec_h264。
    
    推荐在生产环境中使用硬件解码。
    """
    
    ax4.text(0.1, 0.5, summary_text, 
             fontsize=11, 
             verticalalignment='center',
             fontfamily='monospace',
             bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.3))
    
    # 调整布局
    plt.tight_layout()
    
    # 保存图表
    output_file = 'cpu_comparison.png'
    plt.savefig(output_file, dpi=300, bbox_inches='tight')
    print(f"✅ 图表已保存: {output_file}")
    
    # 显示图表
    try:
        plt.show()
    except:
        print("⚠️  无法显示图表（可能没有X11显示），但已保存到文件")

def print_summary():
    """打印文本摘要"""
    sw_times, sw_cpu = read_cpu_data('cpu_avdec_h264.csv')
    hw_times, hw_cpu = read_cpu_data('cpu_enrigindec.csv')
    
    if not sw_cpu or not hw_cpu:
        return
    
    sw_stats = calculate_stats(sw_cpu)
    hw_stats = calculate_stats(hw_cpu)
    
    print("\n" + "="*60)
    print("CPU占用对比摘要")
    print("="*60)
    print(f"\n{'指标':<15} {'avdec_h264':<15} {'enrigindec':<15} {'差异':<15}")
    print("-"*60)
    print(f"{'平均CPU':<15} {sw_stats['mean']:>10.2f}%    {hw_stats['mean']:>10.2f}%    {sw_stats['mean']-hw_stats['mean']:>8.2f}% ⬇️")
    print(f"{'最大CPU':<15} {sw_stats['max']:>10.2f}%    {hw_stats['max']:>10.2f}%    {sw_stats['max']-hw_stats['max']:>8.2f}% ⬇️")
    print(f"{'最小CPU':<15} {sw_stats['min']:>10.2f}%    {hw_stats['min']:>10.2f}%    {sw_stats['min']-hw_stats['min']:>8.2f}% ⬇️")
    print(f"{'标准差':<15} {sw_stats['std']:>10.2f}%    {hw_stats['std']:>10.2f}%    {sw_stats['std']-hw_stats['std']:>8.2f}% ⬇️")
    print("="*60 + "\n")

if __name__ == '__main__':
    print("🎨 生成CPU占用对比图表...")
    print_summary()
    plot_comparison()
